package com.adtec.base.cloud.xxljobservise.xxljob.xxljob.service;

import com.adtec.base.cloud.xxljobservise.xxljob.xxljob.utils.CheckIpAndPortUtil;
import com.adtec.base.cloud.xxljobservise.xxljob.xxljob.utils.CmdUtil;
import com.adtec.base.cloud.xxljobservise.xxljob.xxljob.utils.ExecuteSQLUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;

@Slf4j
@Component
public class ResetJobService {
    @Autowired
    ExecuteSQLUtil executeSQLUtil;
    @Autowired
    CheckIpAndPortUtil checkIpAndPortUtil;
    @Autowired
    CmdUtil cmdUtil;

    private String sysShellUrl = "/home/EnterpriseWeChatHospitalSystem/doc/shell/";


    @XxlJob("resetSystemJobHandler")
    public ReturnT<String> resetSystemJobHandler(String param) throws Exception {
        XxlJobLogger.log(param);
        Connection connection = executeSQLUtil.executeSql("./doc/sql/reset/resetsys.sql");
        return ReturnT.SUCCESS;
    }

    @XxlJob("guardGatewayJobHandler")
    public ReturnT<String> guardGatewayJobHandler(String operate) throws Exception {
        //监控本地某个服务并在服务宕机后自动重启
        XxlJobLogger.log("需要执行的操作:" + operate);
        String nativeIP = checkIpAndPortUtil.getNativeIP();
//        String sysShellUrl = "/home/EnterpriseWeChatHospitalSystem/";
        int port = 8777;
        String serverShell = "gateway.sh";
        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
    }

    @XxlJob("guardRbacJobHandler")
    public ReturnT<String> guardRbacJobHandler(String operate) throws Exception {
        //监控本地某个服务并在服务宕机后自动重启
        XxlJobLogger.log("需要执行的操作:" + operate);
        String nativeIP = checkIpAndPortUtil.getNativeIP();
        int port = 8401;
        String serverShell = "rbac.sh";
        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
    }

    @XxlJob("guardSmsJobHandler")
    public ReturnT<String> guardSmsJobHandler(String operate) throws Exception {
        //监控本地某个服务并在服务宕机后自动重启
        XxlJobLogger.log("需要执行的操作:" + operate);
        String nativeIP = checkIpAndPortUtil.getNativeIP();
        int port = 8402;
        String serverShell = "sms.sh";
        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
    }

//    @XxlJob("guardHospitalJobHandler")
//    public ReturnT<String> guardHospitalJobHandler(String operate) throws Exception {
//        //监控本地某个服务并在服务宕机后自动重启
//        XxlJobLogger.log("需要执行的操作:"+operate);
//        String nativeIP = checkIpAndPortUtil.getNativeIP();
//        int port = 8403;
//        String serverShell = "hospital.sh";
//        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
//    }

    @XxlJob("guardWechatJobHandler")
    public ReturnT<String> guardWechatJobHandler(String operate) throws Exception {
        //监控本地某个服务并在服务宕机后自动重启
        XxlJobLogger.log("需要执行的操作:" + operate);
        String nativeIP = checkIpAndPortUtil.getNativeIP();
        int port = 8403;
        String serverShell = "wechat.sh";
        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
    }

    @XxlJob("guardCommunicateJobHandler")
    public ReturnT<String> guardCommunicateJobHandler(String operate) throws Exception {
        //监控本地某个服务并在服务宕机后自动重启
        XxlJobLogger.log("需要执行的操作:" + operate);
        String nativeIP = checkIpAndPortUtil.getNativeIP();
        int port = 8405;
        String serverShell = "communicate.sh";
        return this.guardSystemJob(nativeIP, port, sysShellUrl, serverShell, operate);
    }


    private ReturnT<String> guardSystemJob(String nativeIP, int port, String sysShellUrl, String serverShell, String operate) {
        //规范输入的参数
        if (StringUtils.isBlank(operate)) {
            operate = "restart";
            XxlJobLogger.log("输入参数有误默认执行" + operate);

        } else {
            if (!operate.equalsIgnoreCase("stop") && !operate.equalsIgnoreCase("restart")) {
                operate = "restart";
                XxlJobLogger.log("输入参数有误默认执行" + operate);
            }
        }
        if (operate.equalsIgnoreCase("stop")) {
            try {
                String execCmd = cmdUtil.execCmd(sysShellUrl + serverShell + " -" + operate, null);
                XxlJobLogger.log(execCmd);
                return new ReturnT<String>(IJobHandler.SUCCESS.getCode(), nativeIP + ":" + port + "服务成功停止");
            } catch (Exception e) {
                return new ReturnT<String>(IJobHandler.FAIL.getCode(), nativeIP + ":" + port + "shell脚本异常无法停止服务" + e);
            }
        } else {
            boolean telnetIpAndPort = checkIpAndPortUtil.telnetIpAndPort(nativeIP, port);
            if (telnetIpAndPort) {
                XxlJobLogger.log(nativeIP + ":" + port + "服务正常");
                return new ReturnT<String>(IJobHandler.SUCCESS.getCode(), nativeIP + ":" + port + "服务正常");
            } else {
                log.warn(nativeIP + ":" + port + "服务不正常");
                try {
                    String execCmd = cmdUtil.execCmd(sysShellUrl + serverShell + " -" + operate, null);
//                String execCmd = cmdUtil.execCmd("sh ./hospital.sh -restart", null);
                    XxlJobLogger.log(execCmd);
                    boolean telnetIpAndPortRecall = false;
                    XxlJobLogger.log("重启中....每10秒检查服务是否正常,检查三次");
                    for (int i = 0; i < 3; i++) {
                        XxlJobLogger.log("第" + (i + 1) + "次检查...");
                        Thread.sleep(10000);
                        telnetIpAndPortRecall = checkIpAndPortUtil.telnetIpAndPort(nativeIP, port);
                        if (telnetIpAndPortRecall) {
                            break;
                        }
                    }
                    if (telnetIpAndPortRecall) {
                        return new ReturnT<String>(IJobHandler.SUCCESS.getCode(), nativeIP + ":" + port + "服务成功重启");
                    } else {
                        return new ReturnT<String>(IJobHandler.FAIL_TIMEOUT.getCode(), nativeIP + ":" + port + "服务在等待时间内重启失败,请手动检查服务状态");
                    }
                } catch (Exception e) {
                    return new ReturnT<String>(IJobHandler.FAIL.getCode(), nativeIP + ":" + port + "服务异常,且无法重启服务" + e);
                }
            }
        }
    }
}
